{ config, lib, pkgs, ... }:
with lib;
let
  cfg = config.roles.server.nextcloud;
in {
  options.roles.server.nextcloud = {
    enable = mkOption {
      default = false;
      type = types.bool;
    };
    domain = mkOption {
      default = config.roles.server.domain;
      type = types.str;
    };
    adminpassFile = mkOption {
      default = "${pkgs.writeText "nextcloudPass" "pass"}";
      type = types.str;
    };
    home = mkOption {
      default = "/var/lib/nextcloud";
      type = types.str;
    };
  };

  config = mkIf cfg.enable {
    roles.server.nginx.enable = mkForce true;

    services = {
      nextcloud = {
        enable = true;
        config = {
          dbtype = "pgsql";
          inherit (cfg) adminpassFile;
        };
        database.createLocally = true;
        inherit (cfg) home;
        hostName = "cloud." + cfg.domain;
        maxUploadSize = "50G";
        phpOptions."opcache.interned_strings_buffer" = "16";
        settings.overwriteprotocol = "https";
      };

      nginx.virtualHosts.${config.services.nextcloud.hostName} = {
        forceSSL = true;
        useACMEHost = cfg.domain;
        extraConfig = ''
          add_header Strict-Transport-Security "max-age=15552000; includeSubDomains" always;
        '';
      };
    };
  };
}
